package com.sc.server.member.config;

import com.sc.server.member.config.annotation.CheckLogin;
import com.sc.server.member.cons.MemberCons;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

//import org.apache.commons.lang.StringUtils;

/**
 * @author yuantongqin
 * desc:
 * 2020-05-24
 */
@Component
@Slf4j
public class LoginIntercept implements HandlerInterceptor {

    /**
     * 1. loginName,sessionId
     * 2. accessToken
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("member-server 拦截器中");
        if(handler != null && handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            CheckLogin annotation = AnnotationUtils.findAnnotation(handlerMethod.getBean().getClass(), CheckLogin.class);
            if(annotation != null){
//                Optional<Cookie> loginName = Stream.of(request.getCookies()).filter(cookie -> StringUtils.equals("loginName", cookie.getName())).findFirst();
//                String value = loginName.get().getValue();
//                if(StringUtils.isEmpty(value)){
//                    return false;
//                }
//                // 查询数据库
//                if("张三".equals(value)){
//                    LoginContext.builder().setUserId(1L).build();
//                }else{
//                    LoginContext.builder().setUserId(2L).build();
//                }
//                Cookie cookie = new Cookie("sessionId",LoginContext.getUserId()+"");
//                cookie.setHttpOnly(true);
//                cookie.setPath("/");
//                cookie.setMaxAge(24*60*60);
//                response.addCookie(cookie);
                return true;
            }
        }

        return initTraceId(request);
    }

    /**
     * 设置traceID
     */
    private boolean initTraceId(HttpServletRequest request) {
        String traceRootId = request.getHeader(MemberCons.TRACE_ROOT_ID);
        if (StringUtils.isEmpty(traceRootId)) {
            traceRootId = UUID.randomUUID().toString().replace("-", "");
        }
        MDC.put(MemberCons.TRACE_ROOT_ID, traceRootId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String traceRootId = request.getHeader(MemberCons.TRACE_ROOT_ID);
        if (!StringUtils.isEmpty(traceRootId)) {
            MDC.remove(traceRootId);
        }
        // 溢出记录
        LoginContext.remove();

    }
}
